package com.ruoyi.service.fileshare.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.domain.fileshare.entity.SysFile;
import com.ruoyi.service.fileshare.EmailService;
import com.ruoyi.system.service.ISnowflakeService;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private ISnowflakeService snowflakeService;

    @Override
    public MimeMessage buildMimeMessage(String id,String sender, List<String> recipients, String title, String content, List<SysFile> attachments) {
        //  处理待发送数据
        if (CollectionUtils.isEmpty(recipients)) {
            throw new ServiceException("邮件接收人不能为空。");
        }
        if (!StringUtils.hasLength(sender)) {
            throw new ServiceException("邮件发送人不能为空。");
        }
        var sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        var strDate = sdf.format(new Date());

        if (!StringUtils.hasLength(content)) {
            content = "<p>采购文件共享。</p>";
        }
        else{
            content = "<p>"+content+"</p>";
        }
        var contentBuilder = new StringBuilder(content);
        contentBuilder.append("<br/><br/><hr/>");
        contentBuilder.append("<br/><i style=\"font-size:10px;\">-文件发送时间：").append(strDate).append("-</i>");
        contentBuilder.append("<br/><i style=\"font-size:10px;\">-邮件唯一识别码：").append(id).append("-</i>");
        try {
            var message = mailSender.createMimeMessage();
            var messageHelper = new MimeMessageHelper(message, true);
            // 设置基础属性
            messageHelper.setFrom(sender);
            messageHelper.setTo(recipients.toArray(new String[0]));
            messageHelper.setSubject(title);
            messageHelper.setText(contentBuilder.toString(), true);
            messageHelper.setSentDate(new Date());
            if (CollectionUtils.isEmpty(attachments)) {
                return message;
            }
            for (SysFile attachment : attachments) {
                var attach = new File(attachment.getPath());
                messageHelper.addAttachment(attachment.getOriginalName(), attach);
            }
            return message;
        } catch (MessagingException e) {
            throw new ServiceException("邮件创建失败：" + e.getMessage());
        }
    }

    @Override
    public MimeMessage buildMimeMessageCompressAttachments(String id,String sender, List<String> recipients, String title, String content, List<SysFile> attachments) {
        //  处理待发送数据
        if (CollectionUtils.isEmpty(recipients)) {
            throw new ServiceException("邮件接收人不能为空。");
        }
        if (!StringUtils.hasLength(sender)) {
            throw new ServiceException("邮件发送人不能为空。");
        }
        // 压缩附件attachments为一个zip压缩包
        File zipFile = null;
        try {
            zipFile = File.createTempFile("attachments-"+id, ".zip");
            try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))) {
                for (SysFile attachment : attachments) {
                    File file = new File(attachment.getPath());
                    if (file.exists()) {
                        ZipEntry zipEntry = new ZipEntry(attachment.getOriginalName());
                        zipOut.putNextEntry(zipEntry);
                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] bytes = new byte[1024];
                            int length;
                            while ((length = fis.read(bytes)) >= 0) {
                                zipOut.write(bytes, 0, length);
                            }
                        }
                        zipOut.closeEntry();
                    }
                }
            }
            var strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            if (!StringUtils.hasLength(content)) {
                content = "<p>采购文件共享。</p>";
            }
            else{
                content = "<p>"+content+"</p>";
            }
            String contentBuilder = content + "<br/><br/><hr/>" +
                    "<br/><i style=\"font-size:10px;\">-文件发送时间：" + strDate + "-</i>" +
                    "<br/><i style=\"font-size:10px;\">-邮件唯一识别码：" + id + "-</i>";
            var message = mailSender.createMimeMessage();
            var messageHelper = new MimeMessageHelper(message, true);
            // 设置基础属性
            messageHelper.setFrom(sender);
            messageHelper.setTo(recipients.toArray(new String[0]));
            messageHelper.setSubject(title);
            messageHelper.setText(contentBuilder, true);
            messageHelper.setSentDate(new Date());
            messageHelper.addAttachment("share-attachments.zip", zipFile);
            return message;
        } catch (Exception e) {
            throw new ServiceException("邮件构建失败：" + e.getMessage());
        }finally {
//            if (zipFile != null) {
//                zipFile.delete();
//            }
        }
    }

    @Override
    @Async
    public void send(MimeMessage message) {
        try {
            mailSender.send(message);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
